// miniprogram/pages/consumption/edit/edit.js
const db = wx.cloud.database()
const _ = db.command
Page({
  data: {
    formData: {},
    loading: false,
    delLoading: false,
    isHaveClick: false
  },
  onLoad: function (options) {
    this.setData({
      formData: JSON.parse(options.data)
    })
  },
  input: function (e) {
    let key = e.currentTarget.dataset.key
    let value = e.detail.value
    this.setData({
      ['formData.' + key]: value
    })
  },
  save: function () {
    if(this.data.isHaveClick) return
    let submitData = this.data.formData
    if (submitData.content == '') {
      wx.showToast({
        title: '消费说明不能为空',
        icon: 'none'
      })
      return
    }
    if (submitData.content.length < 3) {
      wx.showToast({
        title: '消费说明不能少于三个字！',
        icon: 'none'
      })
      return
    }
    if (submitData.money == '') {
      wx.showToast({
        title: '消费金额不能为空',
        icon: 'none'
      })
      return
    }
    var priceReg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
    if (!priceReg.test(submitData.money)) {
      wx.showToast({
        title: '请输入正确的消费金额！',
        icon: 'none'
      })
      return
    }
    if (submitData.money <= 100 && submitData.money >= 0) submitData.className = 'green-border'
    if (submitData.money <= 500 && submitData.money >= 101) submitData.className = 'yellow-border'
    if (submitData.money <= 1000 && submitData.money >= 501) submitData.className = 'orange-border'
    if (submitData.money <= 5000 && submitData.money >= 1001) submitData.className = 'orange-red-border'
    if (submitData.money >= 5000) submitData.className = 'red-border'
    submitData.updata_time = new Date()
    submitData.money = parseFloat(submitData.money)
    this.setData({
      loading: true,
      isHaveClick: true
    })
    db.collection('consume').doc(submitData._id).update({
      data: {
        money: submitData.money,
        content: submitData.content,
        updata_time: new Date()
      },
    }).then(res => {
      wx.hideLoading()
      wx.showToast({
        title: '保存成功！'
      })
      this.setData({
        loading: false
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 2
        })
      }, 1500)
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: JSON.stringify(err),
        icon: 'none'
      })
    })
  },
  del: function() {
    if(this.data.isHaveClick) return
    this.setData({
      delLoading: true,
      isHaveClick: true
    })
    db.collection('consume').doc(this.data.formData._id).remove().then(res => {
      wx.hideLoading()
      wx.showToast({
        title: '删除成功！'
      })
      this.setData({
        delLoading: false
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 2
        })
      }, 1500)
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: JSON.stringify(err),
        icon: 'none'
      })
    })
  }
})